﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Authority.Client
{
    public class RequestHelper
    {
        /// <summary>
        /// 获取接口内容，获取html信息，常用于查询指定url的内容信息
        /// </summary>
        /// <param name="url">接口地址</param>
        /// <param name="method">GET或者POST</param>
        /// <param name="pEncoding">字符编码</param>
        /// <param name="content">成功则返回内容，失败则返回错误信息</param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static bool GetHtml(string url, string method, Encoding pEncoding, out string content, int timeOut = 30000)
        {
            bool bReturn = false;
            int num = 0;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            string szContent = string.Empty;
            #region 模拟百度爬虫
            request.UserAgent = "User-Agent: Mozilla/5.0+(Windows+NT+6.0;+WOW64;+rv:31.0)+Gecko/20100101+Firefox/31.0";
            //Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
            request.Accept = "*/*";
            //request.KeepAlive = true;
            request.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
            request.Headers.Add("Authorization", MakeAuthorationHeaderValue(url));
            #endregion

            request.Method = method;

            //给post请求增加请求数据
            if (method.ToLower() == "post")
            {
                string data = url.Substring(url.IndexOf("?") + 1);
                byte[] byteArray = pEncoding.GetBytes(data);
                request.ContentLength = byteArray.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(byteArray, 0, byteArray.Length);
                stream.Close();
            }

            //request.Method = method;
            request.MaximumAutomaticRedirections = int.MaxValue;
            //允许请求重定向  默认值为false
            request.AllowAutoRedirect = true;
            request.Timeout = timeOut;
           // LogUtility.WriteLog(request.ToJSON());
            while (num < 3 && string.IsNullOrEmpty(szContent))
            {
                try
                {

                    HttpWebResponse objResponse = request.GetResponse() as HttpWebResponse;
                    if (objResponse.StatusCode == HttpStatusCode.OK)
                    {
                        Stream objStream = objResponse.GetResponseStream();
                        StreamReader objStreamReader = new StreamReader(objStream, pEncoding);
                        objStream.ReadTimeout = 15000;
                        szContent = objStreamReader.ReadToEnd();
                        objStreamReader.Close();
                        objStreamReader.Dispose();
                        objResponse.Close();
                        bReturn = true;
                    }
                    else
                    {
                        szContent = "接口服务出错";
                       // LogHelper.Error(szContent + "URL地址：" + url);
                    }

                }
                catch (Exception ex)
                {
                    bReturn = false;
                    szContent = ex.Message;
                    //LogUtility.WriteLog(ex.Message+ex.StackTrace);
                    //  LogHelper.Error("发起网络请求时出错,URL地址：" + url);
                    //  LogHelper.Error(ex);
                    // ApiLogHelper.Error(ex, url);
                }
                finally
                {
                    num++;
                }
            }
            content = szContent;
            return bReturn;

        }

        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string MakeAuthorationHeaderValue(string url)
        {
            string szReturn = string.Empty;
            var scheme = "BMCW ";
            string key = "cgs";

            int ms = DateTime.Now.Millisecond;
            if (ms < 100)
            {
                ms += 100;
            }
            string token;
            if (url.Length > 32)
            {
                token = key + url.Substring(8, 24) + ms;
            }
            else
            {
                token = key + url.Substring(9) + ms;
            }
            szReturn = ms + MD5String(token);
            return scheme + szReturn;
        }

        /// <summary>
        /// MD5加密字符串
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        public static string MD5String(string input)
        {
            if (input == null)
            {
                return null;
            }

            MD5 md5Hash = MD5.Create();

            // 将输入字符串转换为字节数组并计算哈希数据 
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // 创建一个 Stringbuilder 来收集字节并创建字符串 
            StringBuilder sBuilder = new StringBuilder();

            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // 返回十六进制字符串 
            return sBuilder.ToString();
        }


    }


}
